package cn.rokhdelar.ams.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.rokhdelar.ams.common.domain.vo.PageVO;
import cn.rokhdelar.ams.management.domain.po.SysDictionary;
import cn.rokhdelar.ams.management.domain.po.SysDictionaryItem;
import cn.rokhdelar.ams.management.domain.query.DictionaryQuery;
import cn.rokhdelar.ams.management.domain.vo.DictionaryVO;
import cn.rokhdelar.ams.management.mapper.SysDictionaryItemMapper;
import cn.rokhdelar.ams.management.mapper.SysDictionaryMapper;
import cn.rokhdelar.ams.management.service.SysDictionaryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Rokhdelar
 * @since 2024/10/21 -- 17:04
 **/

@Service
@RequiredArgsConstructor
public class SysDictionaryServiceImpl extends ServiceImpl<SysDictionaryMapper, SysDictionary>
        implements SysDictionaryService {
    private final SysDictionaryItemMapper itemMapper;
    /**
     * @param query 查询参数
     * @return 分页对象
     */
    @Override
    @Transactional
    public PageVO<DictionaryVO> getDictionaryListByPage(DictionaryQuery query) {
        Page<SysDictionary> page = query.toPageDefaultSortByCreateTime();

        Page<SysDictionary> dictionaryPage = lambdaQuery()
                .like(query.getName() != null, SysDictionary::getName, query.getName())
                .page(page);

        return PageVO.of(dictionaryPage, DictionaryVO.class);
    }

    @Override
    @Transactional
    public DictionaryVO getDictionaryById(String id) {
        return BeanUtil.copyProperties(getById(id), DictionaryVO.class);
    }

    @Override
    @Transactional
    public Boolean deleteById(String id) {
        LambdaQueryWrapper<SysDictionaryItem> queryWrapper = new LambdaQueryWrapper<SysDictionaryItem>()
                .eq(SysDictionaryItem::getDictionaryId, id);
        if (itemMapper.selectCount(queryWrapper) != 0L) {
            throw new RuntimeException("该字典存在字典项，不允许删除。");
        }

        return removeById(id);
    }
}
